<template>
  <a-form ref="formInstance" :model="apiData" layout="vertical" :rules="rules">
    <a-row :gutter="gutter">
      <a-col :span="12">
        <a-form-item label="Client Name" name="FullName">
          <a-tooltip
            :visible="nameIsExist.exits"
            placement="left"
            :get-popup-container="triggerNode => triggerNode.parentNode"
          >
            <template #title> Already have a client named {{ nameIsExist.name }} </template>
            <a-input v-model:value="apiData.FullName" @blur="checkClientNameExist" />
          </a-tooltip>
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="Abbreviation" name="ShortName">
          <a-input v-model:value="apiData.ShortName" />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="gutter">
      <a-col :span="12">
        <a-form-item label="Organization" name="ParentID">
          <a-select
            v-model:value="apiData.ParentID"
            style="width: calc(100% - 100px)"
            :get-popup-container="triggerNode => triggerNode.parentNode"
            show-search
            class="addable"
            placeholder="Please select or input to create"
            option-filter-prop="label"
          >
            <!-- 数据库中已有的 -->
            <a-select-option v-for="item in dict.organizations" :key="item.value" :label="item.text">
              {{ item.text }}
            </a-select-option>
            <!-- 用户手动添加的 -->
            <a-select-option v-for="item in tempOrganizations" :key="item.value" :label="item.text">
              {{ item.text }}
            </a-select-option>
          </a-select>
          <a-button type="primary" ghost style="width: 96px; margin-left: 4px" @click="showAddOrganization = true">
            <a-space>
              <e-icon type="add" font-size="16px" />
              Create
            </a-space>
          </a-button>
        </a-form-item>
        <a-modal
          v-model:visible="showAddOrganization"
          width="888px"
          title="Create New Organization"
          wrap-class-name="primary-modal"
          ok-text="Save"
          :destroyOnClose="true"
          @cancel="showAddOrganization = false"
        >
          <a-form ref="addOrganizationFormRef" layout="vertical" :model="organizationFormForAdd">
            <a-form-item label="Organization Name" :rules="addOrganizationRules" name="name">
              <a-input v-model:value="organizationFormForAdd.name" placeholder="Please Input Organization Name" />
            </a-form-item>
          </a-form>
          <template #footer>
            <a-button key="back" @click="showAddOrganization = false">Cancel</a-button>
            <a-button key="submit" :loading="buttonLoading" type="primary" @click="handleAddOrganization">
              Create
            </a-button>
          </template>
        </a-modal>
      </a-col>
      <a-col :span="12">
        <a-form-item label="Client Nature" name="ClientKind">
          <e-radio v-model="apiData.ClientKind" :options="dict.clientTypes" />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="gutter">
      <a-col :span="12">
        <a-form-item name="ClientTier">
          <template #label>
            <client-tier-tip />
          </template>
          <a-select v-model:value="apiData.ClientTier" :get-popup-container="triggerNode => triggerNode.parentNode">
            <a-select-option v-for="item in dict.clientTiers" :key="item.value">
              {{ item.text }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="Country/Region" name="CountryID">
          <e-country-region-select v-model="CountryIDWrapped" :allow-clear="true" />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="gutter">
      <a-col :span="12">
        <a-form-item label="E-mail" name="Email">
          <a-input v-model:value="apiData.Email" @blur="() => (apiData.Email = apiData.Email.trim())" />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="Time Zone" name="TimeZone">
          <a-select
            v-model:value="apiData.TimeZone"
            show-search
            option-filter-prop="label"
            :get-popup-container="triggerNode => triggerNode.parentNode"
          >
            <a-select-option v-for="item in dict.timeZones" :key="item.value" :label="item.text">
              {{ item.text }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="gutter">
      <a-col :span="12">
        <a-form-item name="Url">
          <template #label>
            <url-tip />
          </template>
          <a-input v-model:value="apiData.Url" @blur="() => (apiData.Url = apiData.Url.trim())" />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="Business Area" name="BusinessDirection">
          <e-radio v-model="apiData.BusinessDirection" :options="dict.businessAreas" />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="gutter">
      <a-col :span="12">
        <a-form-item label="Client Industry" name="SaleBUID">
          <a-select
            v-model:value="apiData.SaleBUID"
            show-search
            option-filter-prop="label"
            :get-popup-container="triggerNode => triggerNode.parentNode"
          >
            <a-select-option v-for="item in dict.salesBUs" :key="item.value" :label="item.text">
              {{ item.text }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="My BU" name="hrSalesBUID">
          <a-select
            v-model:value="hrSalesBUIDWrapped"
            :disabled="dict.myBUs.findIndex(bu => bu.value === apiData.SaleBUID) > -1"
            show-search
            option-filter-prop="label"
            :get-popup-container="triggerNode => triggerNode.parentNode"
          >
            <a-select-option v-for="item in dict.myBUs" :key="item.value" :label="item.text">
              {{ item.text }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="gutter">
      <a-col :span="12">
        <a-form-item label="Currency" name="Currency">
          <a-select
            v-model:value="CurrencyWrapped"
            show-search
            allow-clear
            option-filter-prop="label"
            :get-popup-container="triggerNode => triggerNode.parentNode"
          >
            <a-select-option v-for="item in dict.currencies" :key="item.value" :label="item.text">
              {{ item.text }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="Operate BU" name="OperateBU">
          <a-select
            v-model:value="OperateBUWrapped"
            show-search
            allow-clear
            option-filter-prop="label"
            :get-popup-container="triggerNode => triggerNode.parentNode"
          >
            <a-select-option v-for="item in dict.operateBUs" :key="item.value" :label="item.text">
              {{ item.text }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="gutter">
      <a-col :span="24">
        <a-form-item label="Remark" name="Comment">
          <a-textarea v-model:value="apiData.Comment" :auto-size="{ minRows: 4, maxRows: 4 }" />
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { useStore } from 'vuex'
import Utils from '@/utils'
import ECountryRegionSelect from '@/components/ECountryRegionSelect.vue'
import TargetClient from '@/api/targetClient.js'
import { useDictNullValue } from '@/hooks/useDictNullValue.js'
import ERadio from '@/components/ERadio.vue'
import ClientTierTip from '@/pages/components/ClientTierTip.vue'
import UrlTip from '@/pages/components/URLTip.vue'
import { useAddNewOrganization } from '@/pages/Client/hooks/useAddNewOrganization.js'
const store = useStore()
const dict = ref(computed(() => store.state.dict))
const gutter = [120, 16]
const formInstance = ref(null)
const apiData = reactive({
  // 客户名称（Client Name）
  FullName: '',
  // 客户简称（Abbreviation）
  ShortName: '',
  // 客户组织（Organization）
  ParentID: '',
  // 客户性质（Client Nature）
  ClientKind: '',
  // 客户等级（Client Tier）
  ClientTier: 5,
  // 国家与地区（Country/Region）
  CountryID: 0,
  // 电子邮箱（E-mail）
  Email: '',
  // 时区（Time zone）
  TimeZone: '',
  // 网站（URL）
  Url: '',
  // 商业区域（Business Area）
  BusinessDirection: '',
  // 客户所属销售 BU（Sales BU）
  SaleBUID: '',
  // MyBU（Hr BU）
  hrSalesBUID: 0,
  // 运营BU
  OperateBU: 0,
  // 币种
  Currency: 0,
  // 备注（Remark）
  Comment: ''
})
const CountryIDWrapped = useDictNullValue(apiData, 'CountryID')
const CurrencyWrapped = useDictNullValue(apiData, 'Currency')
const OperateBUWrapped = useDictNullValue(apiData, 'OperateBU')
const hrSalesBUIDWrapped = computed({
  get() {
    if (dict.value.myBUs.findIndex(bu => bu.value === apiData.SaleBUID) > -1) {
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      apiData.hrSalesBUID = apiData.SaleBUID
    }
    if (apiData.hrSalesBUID === 0) return ''
    return apiData.hrSalesBUID
  },
  set(val) {
    apiData.hrSalesBUID = val
  }
})
// 新建组织
const addOrganizationFormRef = ref(null)
const {
  organizationFormForAdd,
  tempOrganizations,
  showAddOrganization,
  addOrganizationRules,
  buttonLoading,
  handleAddOrganization
} = useAddNewOrganization(addOrganizationFormRef, dict, apiData)
store.dispatch('dict/getOrganizations').then(() => {
  if (dict.value.organizations.length > 0) apiData.ParentID = dict.value.organizations[0].value
})
store.dispatch('dict/getClientTypes').then(() => {
  if (dict.value.clientTypes.length > 0) apiData.ClientKind = dict.value.clientTypes[0].value
})
store.dispatch('dict/getClientTiers')
store.dispatch('dict/getTimeZones').then(() => {
  if (dict.value.timeZones.length > 0) apiData.TimeZone = dict.value.timeZones[0].value
})
store.dispatch('dict/getBusinessAreas').then(() => {
  if (dict.value.businessAreas.length > 0) apiData.BusinessDirection = dict.value.businessAreas[0].value
})
store.dispatch('dict/getSalesBUs').then(() => {
  if (dict.value.salesBUs.length > 0) apiData.SaleBUID = dict.value.salesBUs[0].value
})
// 如果获取不到myBU则myBU非必填
store.dispatch('dict/getMyBUs').then(() => {
  if (dict.value.myBUs.length > 0) {
    apiData.hrSalesBUID = dict.value.myBUs[0].value
  } else {
    rules.hrSalesBUID[0].required = false
  }
})
store.dispatch('dict/getCurrencies')
store.dispatch('dict/getOperateBUs')
const rules = reactive({
  FullName: [
    {
      required: true,
      whitespace: true,
      message: 'Please input Client Name',
      trigger: 'blur'
    }
  ],
  ShortName: [
    {
      required: true,
      whitespace: true,
      message: 'Please input Abbreviation',
      trigger: 'blur'
    },
    {
      asyncValidator: (rule, value) => TargetClient.isUniqueAbbreviation(rule, value),
      message: 'Abbreviation is exist',
      trigger: 'blur'
    }
  ],
  ParentID: [
    {
      type: 'number',
      required: true,
      message: 'Please select a organization',
      trigger: 'change'
    },
    {
      validator: (rule, value) => {
        return value !== 0 ? Promise.resolve() : Promise.reject(new Error())
      },
      message: 'Please select',
      trigger: 'blur'
    }
  ],
  ClientKind: [
    {
      type: 'number',
      required: true,
      message: 'Please select the client nature',
      trigger: 'change'
    }
  ],
  ClientTier: [
    {
      type: 'number',
      required: true,
      min: 1,
      message: 'Please select the client tier',
      trigger: 'change'
    }
  ],
  CountryID: [
    {
      type: 'number',
      required: true,
      min: 1,
      message: 'Please select the Country/Region',
      trigger: 'change'
    }
  ],
  Email: [
    {
      required: true,
      whitespace: true,
      message: 'Please input E-mail',
      trigger: 'blur'
    },
    {
      type: 'email',
      message: 'Incorrect email address format',
      trigger: 'blur'
    }
  ],
  TimeZone: [
    {
      required: true,
      message: 'Please select a time zone',
      trigger: 'change'
    }
  ],
  Url: [
    {
      required: true,
      whitespace: true,
      message: 'Please input url',
      trigger: 'blur'
    },
    {
      validator: (rule, value) => {
        const regex = Utils.getRegex('url')
        const urls = value.split(';').filter(url => url.trim() !== '')
        if (urls.length > 0 && urls.length === value.split(';').length && urls.every(url => regex.test(url.trim()))) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error())
        }
      },
      message:
        'Incorrect url address format. eg. https://google.com, If there are multiple URLs, separate them by semicolons.',
      trigger: 'blur'
    },
    {
      asyncValidator: (rule, value) => TargetClient.isUniqueUrl(rule, value, undefined, apiData.ParentID),
      message: 'This URL already exists in another organization.',
      trigger: 'blur'
    }
  ],
  BusinessDirection: [
    {
      type: 'number',
      required: true,
      message: 'Please select a business area',
      trigger: 'change'
    }
  ],
  SaleBUID: [
    {
      type: 'number',
      required: true,
      min: 1,
      message: 'Please select client industry',
      trigger: 'change'
    }
  ],
  hrSalesBUID: [
    {
      type: 'number',
      required: true,
      min: 0,
      message: 'Please select BU',
      trigger: 'change'
    }
  ]
})
const nameIsExist = ref({
  exits: false,
  name: ''
})
watch(
  () => CountryIDWrapped.value,
  countryId => {
    TargetClient.getTimeZoneByCountryID(countryId).then(({ data }) => {
      apiData.TimeZone = data && data !== '0' ? data : ''
    })
  }
)
const checkClientNameExist = () => {
  if (apiData.FullName) {
    TargetClient.isUniqueClientName(apiData.FullName).then(res => {
      if (res.data) {
        nameIsExist.value.exits = true
        nameIsExist.value.name = apiData.FullName
      } else {
        nameIsExist.value.exits = false
      }
    })
  }
}
defineExpose({ formInstance, apiData })
</script>

<style scoped></style>
